<?php
/**
 *
 * Author: Lyu
 * Date: 2023/7/28
 * Time: 14:09
 */

namespace App\OpenApi\AdminApi\Common;

use App\Library\Service\AliCloud\STS;
use App\Library\Service\ExportService;
use App\Library\Service\Upload;
use App\Service\OpenApi\AdminApi\OpenBaseApi;

class CommonApi extends OpenBaseApi
{
    public function uploadImage(): array
    {
        $file = request()->file('file');
        if (empty($file)) {
            return alert_info(1, '请上传图片！');
        }
        return (new Upload())
            ->setMaxFileSize('15M')
            ->setIsThumbPic(false)
            ->setIsUploadCloud(true)
            ->uploadImage($file, 'uploadImage');
    }

    /**
     * 下载导入模板
     * @return array
     */
    public function getImportTemplate()
    {
        $type = $this->input('file_type', 1);
        $path = DIRECTORY_SEPARATOR . 'resource' . DIRECTORY_SEPARATOR . 'template' . DIRECTORY_SEPARATOR . 'file';
        $path = public_path($path);
        $template_url_data = [
            1 => easy_url('download', ['file' => ExportService::encryptFilePath($path . '/用户导入模板1.0.xlsx')]),
            2 => easy_url('download', ['file' => ExportService::encryptFilePath($path . '/批量下单导入模板1.0.xlsx')]),
            3 => easy_url('download', ['file' => ExportService::encryptFilePath($path . '/企业客户批量导入用户模板1.0.xlsx')])
        ];
        if (!array_key_exists($type, $template_url_data)) {
            return alert_info(1, '模板不存在');
        }
        $template_url = isset($template_url_data[$type]) ? $template_url_data[$type] : "";
        return alert_info(0, 'ok', ['jump_url' => $template_url]);
    }

    /**
     * 生成STS临时凭证
     * @return array
     */
    public function ossSts(): array
    {
        $sts_res = STS::assumeRole('admin@' . $this->operate_id);
        if ($sts_res['code'] != 0) {
            return alert_info(1, $sts_res['msg']);
        }
        $credentials = $sts_res['data']['credentials'];
        $credentials['expirationTime'] = strtotime($credentials['expiration']);
        return alert_info(0, 'OK', $credentials);
    }
}
